from xmindparser import xmind_to_dict
from src.core.excelHandler import ExcelHandler

class XMindToExcelConverter:
    @staticmethod
    def convert(xmind_path, excel_path, first_step=None, second_prefix=None, precondition_input = None, test_point_input = None, open_excel=False):
        try:
            workbook_data = xmind_to_dict(xmind_path)
            if not workbook_data:
                return False, "XMind文件解析失败"

            root_topic = workbook_data[0].get('topic')
            if not root_topic:
                return False, "未找到有效根节点"

            root_title = root_topic.get('title', '').strip()
            actual_first_step = first_step if first_step else root_title

            second_level_nodes = []
            if root_topic.get('topics'):
                second_level_nodes = [t for t in root_topic['topics']]

            excel_handler = ExcelHandler(excel_path)
            total_cases = 0

            for node in second_level_nodes:
                sheet_name = node.get('title', '未命名')[:31]
                excel_handler.create_sheet(sheet_name,precondition_input)

                paths = XMindToExcelConverter._collect_paths(node)
                sheet_cases = 0
                for path in paths:
                    if len(path) < 2:
                        continue

                    sheet_cases += 1
                    steps = path[0:-1]
                    # 调用格式化方法
                    formatted_steps = XMindToExcelConverter.format_steps(
                        steps,
                        first_step_desc=actual_first_step,
                        second_prefix=second_prefix
                    )
                    path_last_step = path[-1].replace('\n', '')
                    excel_handler.add_case(
                        sheet_name=sheet_name,
                        test_point=test_point_input,
                        operation="\n".join(formatted_steps),
                        expected_result= f"步骤{len(steps)+1}: {path_last_step}",
                        actual_result=None
                    )

                total_cases += sheet_cases
            excel_handler.save()

            if open_excel:
                excel_handler.open_file()
            return True, f"转换成功，共转换{total_cases}条用例."

        except Exception as e:
            return False, f"转换失败: {str(e)}"


    @staticmethod
    def _collect_paths(node, current_path=None, all_paths=None):
        if current_path is None:
            current_path = []
        if all_paths is None:
            all_paths = []

        title = str(node.get('title', '')).strip()
        new_path = current_path + [title]

        if not node.get('topics'):
            all_paths.append(new_path)
        else:
            for topic in node.get('topics', []):
                XMindToExcelConverter._collect_paths(topic, new_path, all_paths)
        return all_paths

    @staticmethod
    def format_steps(steps, first_step_desc='', second_prefix=''):
        """
        格式化步骤列表，去除标点，支持添加第一步描述和第二步前缀
        参数：
            steps (list): 步骤内容列表
            first_step_desc (str): 第一条步骤描述
            second_prefix (str): 第二条步骤前缀
        返回：
            list: 格式化后的步骤字符串
        """
        formatted = []
        # 第一条步骤，根据配置是否加入描述
        formatted.append(f"1.{first_step_desc}")
        for i, step in enumerate(steps):
            step_temp = step.replace('\n', '')
            if i == 0:
                # 第二条步骤，添加前缀（如果有）
                formatted.append(f"{i + 2}.{second_prefix or ''}{steps[0]}")
            else:
                # 其他步骤
                formatted.append(f"{i + 2}.{step_temp}")
        return formatted